<template>
  <div class="calendar-wrapper">
    <!-- 头部控制栏 -->
    <div class="calendar-header">
      <div class="header-left">
        <div class="date-range">
          {{ displayYear }}年 {{ displayMonthRange }}
        </div>
      </div>
<!--      <div class="header-right">-->
<!--        <el-button-->
<!--            size="small"-->
<!--            @click="changeMonth(-1)"-->
<!--            :disabled="isMinMonth"-->
<!--        >上一个月</el-button>-->
<!--        <el-button-->
<!--            size="small"-->
<!--            @click="resetToCurrent"-->
<!--        >回到今日</el-button>-->
<!--        <el-button-->
<!--            size="small"-->
<!--            @click="changeMonth(1)"-->
<!--            :disabled="isMaxMonth"-->
<!--        >下一个月</el-button>-->
<!--      </div>-->
    </div>

    <!-- 6个日历横向容器 - 优化为一行展示 -->
<!--    <div class="multi-month-container">-->
<!--      <div class="single-month-card" v-for="(monthItem, index) in displayedMonths" :key="monthItem.key">-->
<!--        <t-calendar-->
<!--            :time="monthItem.calendarTime"-->
<!--            :isReset="isReset"-->
<!--            color="#ffffff"-->
<!--            class="compact-calendar"-->
<!--            :term-marks="getMonthTermMarks(monthItem.year, monthItem.month)"-->
<!--        >-->
<!--          <template #header>-->
<!--            <div class="month-title">-->
<!--              {{ monthItem.year }}年{{ monthItem.month }}月-->
<!--            </div>-->
<!--          </template>-->
<!--        </t-calendar>-->
<!--      </div>-->
<!--    </div>-->

    <!-- 步骤指示器 -->
    <div v-if="isInAddingFlow" class="steps-indicator">
      <div class="step-progress-text">当前进度：{{ currentStep }}/3 步</div>
      <div class="step-container">
        <div class="step" :class="{ active: currentStep === 1, completed: currentStep > 1 }">
          <div class="step-number">1</div>
          <div class="step-name">新增学年</div>
        </div>
        <div class="step-line" :class="{ completed: currentStep > 1 }"></div>
        <div class="step" :class="{ active: currentStep === 2, completed: currentStep > 2 }">
          <div class="step-number">2</div>
          <div class="step-name">新增学期</div>
        </div>
        <div class="step-line" :class="{ completed: currentStep > 2 }"></div>
        <div class="step" :class="{ active: currentStep === 3, completed: currentStep > 3 }">
          <div class="step-number">3</div>
          <div class="step-name">新增事件</div>
        </div>
      </div>
    </div>

    <!-- 列表显示区域 -->
    <div v-if="!isInAddingFlow" class="lists-container">
      <!-- 学年列表 -->
      <div v-if="yearInfo.length > 0" class="list-card">
        <div class="list-header">
          <h3 class="list-title">学年列表</h3>
          <el-button
              size="small"
              type="primary"
              @click="startAddingFlow"
          >新增学年计划</el-button>
        </div>
        <el-table :data="sanitizedYearInfo" border style="width: 100%" class="content-table" fit max-height="300">
          <el-table-column prop="yearName" label="学年名称" min-width="120"/>
          <el-table-column prop="yearCode" label="学年代码" min-width="120"/>
          <el-table-column prop="startDate" label="起始日期" min-width="140"/>
          <el-table-column prop="endDate" label="结束日期" min-width="140"/>
          <el-table-column prop="semesterNum" label="学期数" min-width="100"/>
          <el-table-column prop="isDefault" label="是否默认" min-width="100" :formatter="formatBoolean"/>
          <el-table-column prop="status" label="状态" min-width="100" :formatter="formatStatus"/>
          <el-table-column label="操作" min-width="160">
            <template #default="scope">
              <el-button size="small" type="primary" @click="editYear(scope.row)">编辑</el-button>
              <el-button size="small" type="success" @click="addTermsForYear(scope.row)">添加学期</el-button>
              <el-button size="small" type="info">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else-if="yearInfoLoaded" class="empty-state">
        <div class="empty-icon">📅</div>
        <p class="empty-text">暂无学年信息，点击下方按钮创建</p>
        <el-button
            size="small"
            type="primary"
            @click="startAddingFlow"
            class="empty-action-btn"
        >新增学年计划</el-button>
      </div>

      <!-- 学期列表 -->
      <div v-if="termInfo.length > 0" class="list-card">
        <div class="list-header">
          <h3 class="list-title">学期列表</h3>
<!--          <el-button-->
<!--              size="small"-->
<!--              type="primary"-->
<!--              @click="startAddingFlowFromTerm"-->
<!--          >新增学期</el-button>-->
        </div>

        <!-- 学期颜色图例 -->
        <div class="term-legend">
          <div class="legend-title">学期颜色图例：</div>
          <div class="legend-items">
            <div v-for="term in termInfo" :key="term.id" class="legend-item">
              <span class="color-dot" :style="{ backgroundColor: termColorMap[term.id] }"></span>
              <span class="term-name">{{ term.termName }}</span>
            </div>
          </div>
        </div>

        <el-table :data="sanitizedTermInfo" border style="width: 100%" class="content-table" fit max-height="300">
          <el-table-column prop="yearName" label="所属学年" min-width="120"/>
          <el-table-column prop="termCode" label="学期代码" min-width="120"/>
          <el-table-column prop="termName" label="学期名称" min-width="120"/>
          <el-table-column prop="startDate" label="起始日期" min-width="140"/>
          <el-table-column prop="endDate" label="结束日期" min-width="140"/>
          <el-table-column prop="teachingWeeks" label="教学周数" min-width="100"/>
          <el-table-column prop="calendarStartWeek" label="校历第1周" min-width="140"/>
          <el-table-column prop="status" label="状态" min-width="100" :formatter="formatStatus"/>
          <el-table-column label="操作" min-width="160">
            <template #default="scope">
              <el-button size="small" type="primary">编辑</el-button>
              <el-button size="small" type="success" @click="addEventsForTerm(scope.row)">添加事件</el-button>
              <el-button size="small" type="info">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else-if="termInfoLoaded" class="empty-state">
        <div class="empty-icon">📚</div>
        <p class="empty-text">暂无学期信息，请先添加学年</p>
      </div>

      <!-- 事件列表 -->
      <div class="list-card event-list-card">
        <div class="list-header">
          <h3 class="list-title">事件列表</h3>
<!--          <el-button-->
<!--              size="small"-->
<!--              type="primary"-->
<!--              @click="startAddingFlowFromEvent"-->
<!--          >新增事件</el-button>-->
        </div>
        <el-table
            :data="eventsInfo"
            border
            style="width:100%;"
            class="content-table"
            fit
            max-height="400"
        >
<!--          <el-table-column prop="id" label="事件ID" min-width="100"/>-->
<!--          <el-table-column prop="termId" label="学期ID" min-width="100"/>-->
          <el-table-column prop="termName" label="所属学期" min-width="120"/>
          <el-table-column prop="eventName" label="事件名称" min-width="150"/>
          <el-table-column prop="eventType" label="事件类型" min-width="100">
            <template #default="scope">
              {{ eventTypeMap[scope.row.eventType] || '未知' }}
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间" min-width="160"/>
          <el-table-column prop="endTime" label="结束时间" min-width="160"/>
          <el-table-column prop="isActive" label="是否启用" min-width="100" :formatter="formatBoolean"/>
          <el-table-column prop="priority" label="优先级" min-width="100"/>
          <el-table-column prop="notifyBeforeDays" label="提前通知(天)" min-width="120"/>
          <el-table-column prop="description" label="描述" min-width="200"/>
          <el-table-column label="操作" min-width="160">
            <template #default="scope">
              <el-button size="small" type="primary">编辑</el-button>
              <el-button size="small" type="info">详情</el-button>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="eventsInfo.length === 0 && eventsInfoLoaded" class="empty-state inside-card">
          <div class="empty-icon">⏰</div>
          <p class="empty-text">暂无事件信息，请先添加学期</p>
        </div>
      </div>
    </div>

    <!-- 新增流程表单区域 -->
    <div v-if="isInAddingFlow" class="add-container">
      <!-- 步骤1：新增学年表单 -->
      <div v-if="currentStep === 1" class="form-card">
        <div class="form-header">
          <h3>新增学年计划</h3>
          <el-button
              size="small"
              type="text"
              @click="cancelAddingFlow"
          >取消</el-button>
        </div>

        <el-form
            ref="yearFormRef"
            :model="yearForm"
            :rules="yearFormRules"
            label-width="120px"
            class="form-content"
        >
          <el-form-item label="学年名称" prop="yearName">
            <el-input
                v-model="yearForm.yearName"
                placeholder="请输入学年名称（如：2025-2026学年）"
                maxlength="50"
                class="form-input"
            ></el-input>
          </el-form-item>

          <el-form-item label="学年代码" prop="yearCode">
            <el-input
                v-model="yearForm.yearCode"
                placeholder="请输入学年代码（如：2025-2026）"
                maxlength="20"
                class="form-input"
            ></el-input>
          </el-form-item>

          <el-row :gutter="20" class="form-row">
            <el-col :span="12">
              <el-form-item label="起始日期" prop="startDate">
                <el-date-picker
                    v-model="yearForm.startDate"
                    type="date"
                    placeholder="选择起始日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    class="form-input"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期" prop="endDate">
                <el-date-picker
                    v-model="yearForm.endDate"
                    type="date"
                    placeholder="选择结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    class="form-input"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="学期数" prop="semesterNum">
            <el-input-number
                v-model="yearForm.semesterNum"
                :min="1"
                :max="12"
                placeholder="请输入学期数"
                class="form-input"
            ></el-input-number>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select v-model="yearForm.status" placeholder="请选择状态" class="form-input">
              <el-option label="未启用" value="0"></el-option>
              <el-option label="当前" value="1"></el-option>
              <el-option label="已结束" value="2"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="是否默认" prop="isDefault">
            <el-switch
                v-model="yearForm.isDefault"
                active-text="是"
                inactive-text="否"
            ></el-switch>
          </el-form-item>

          <el-form-item label="备注（可选）">
            <el-input
                v-model="yearForm.remark"
                type="textarea"
                rows="3"
                placeholder="请输入备注信息"
                maxlength="200"
                class="form-input"
            ></el-input>
          </el-form-item>

          <el-form-item class="form-buttons">
            <el-button @click="resetYearForm">重置</el-button>
            <el-button type="primary" @click="nextStep" :loading="stepLoading">下一步</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤2：新增学期表单 -->
      <div v-if="currentStep === 2" class="form-card">
        <div class="form-header">
          <h3>批量新增学期 - {{ currentYear.value?.yearName || '未知学年' }}</h3>
          <div class="form-header-actions">
            <span class="form-tip">请先添加完所有学期，再进入事件添加</span>
            <el-button
                size="small"
                type="text"
                @click="cancelAddingFlow"
            >取消</el-button>
          </div>
        </div>

        <!-- 已添加学期列表 -->
        <div class="terms-list" v-if="currentYearTerms.length > 0">
          <div class="terms-list-header">
            <h4>已添加学期（共 {{ currentYearTerms.length }} 个）</h4>
            <el-button size="small" type="danger" @click="batchDeleteTerms" :disabled="!selectedTermIds.length">
              批量删除选中
            </el-button>
          </div>
          <el-table
              :data="currentYearTerms"
              border
              style="width: 100%; margin-bottom: 15px;"
              :max-height="Math.min(currentYearTerms.length * 48 + 50, 300)"
              @selection-change="handleTermSelectionChange"
              class="content-table"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="termName" label="学期名称" min-width="120"/>
            <el-table-column prop="termCode" label="学期代码" min-width="120"/>
            <el-table-column prop="startDate" label="起始日期" min-width="140"/>
            <el-table-column prop="endDate" label="结束日期" min-width="140"/>
            <el-table-column label="操作" min-width="100">
              <template #default="scope">
                <el-button size="small" type="danger" @click="removeTerm(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 学期添加表单 -->
        <el-form
            ref="termFormRef"
            :model="termForm"
            :rules="termFormRules"
            label-width="120px"
            class="form-content term-form"
        >
          <el-form-item label="学期名称" prop="termName">
            <el-input
                v-model="termForm.termName"
                placeholder="请输入学期名称（如：2025-2026学年第一学期）"
                maxlength="50"
                class="form-input"
            ></el-input>
          </el-form-item>

          <el-form-item label="学期代码" prop="termCode">
            <el-input
                v-model="termForm.termCode"
                placeholder="请输入学期代码（如：2025-2026-1）"
                maxlength="20"
                class="form-input"
            ></el-input>
          </el-form-item>

          <el-row :gutter="20" class="form-row">
            <el-col :span="12">
              <el-form-item label="起始日期" prop="startDate">
                <el-date-picker
                    v-model="termForm.startDate"
                    type="date"
                    placeholder="选择起始日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :disabled-date="disableTermStartDate"
                    class="form-input"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期" prop="endDate">
                <el-date-picker
                    v-model="termForm.endDate"
                    type="date"
                    placeholder="选择结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :disabled-date="disableTermEndDate"
                    class="form-input"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="教学周数" prop="semesterNum">
            <el-input-number
                v-model="termForm.semesterNum"
                :min="1"
                :max="52"
                placeholder="请输入教学周数"
                class="form-input"
            ></el-input-number>
          </el-form-item>

          <el-form-item label="校历第1周" prop="calendarStartWeek">
            <el-date-picker
                v-model="termForm.calendarStartWeek"
                type="date"
                placeholder="选择校历第1周起始日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled-date="disableCalendarStartDate"
                class="form-input"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select v-model="termForm.status" placeholder="请选择状态" class="form-input">
              <el-option label="未开始" value="0"></el-option>
              <el-option label="进行中" value="1"></el-option>
              <el-option label="已结束" value="2"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item class="form-buttons">
            <el-button @click="resetTermForm">重置</el-button>
            <el-button type="primary" @click="addTerm" :loading="addTermLoading">添加到学期列表</el-button>
          </el-form-item>
        </el-form>

        <!-- 下一步按钮 -->
        <div class="step-navigation">
          <el-button @click="prevStep">上一步</el-button>
          <el-button type="primary" @click="nextStep" :disabled="currentYearTerms.length === 0" :loading="stepLoading">
            所有学期已添加，进入事件添加
          </el-button>
        </div>
      </div>

      <!-- 步骤3：新增事件表单 -->
      <div v-if="currentStep === 3" class="form-card">
        <div class="form-header">
          <h3>为 {{ currentYear?.yearName || '未知学年' }} 的学期添加事件</h3>
          <div class="form-header-actions">
            <span class="form-tip">每个学期事件独立管理，互不干扰</span>
            <el-button
                size="small"
                type="text"
                style="margin-left: 10px;"
                @click="cancelAddingFlow"
            >取消</el-button>
          </div>
        </div>

        <!-- 容错：无学期数据时显示提示 -->
        <div v-if="!Array.isArray(currentYearTerms) || currentYearTerms.length === 0" class="empty-state inside-form">
          <div class="empty-icon">⚠️</div>
          <p class="empty-text">未找到有效学期数据，请返回上一步重新添加学期</p>
          <el-button size="small" @click="prevStep" class="empty-action-btn">返回上一步</el-button>
        </div>

        <!-- 遍历学期生成独立事件模块 -->
        <div class="term-event-modules" v-else>
          <div
              class="term-event-module"
              v-for="(term, termIndex) in currentYearTerms"
              :key="term.id"
              :class="{ 'active': term.isAddingEvent }"
          >
            <!-- 模块1：学期标题栏 -->
            <div class="module-header">
              <h4>
                {{ termIndex + 1 }}. {{ term.termName || '未命名学期' }}
                <span class="event-count">(已添加事件：{{ term.events?.value?.length || 0 }} 个)</span>
              </h4>
              <el-button
                  size="small"
                  type="primary"
                  @click="toggleEventForm(termIndex)"
              >
                {{ term.isAddingEvent ? '收起表单' : '添加事件' }}
              </el-button>
            </div>

            <!-- 模块2：事件列表 -->
            <div class="event-list-container">
              <el-table
                  v-if="term.events?.value?.length > 0"
                  :data="term.events.value"
                  border
                  size="mini"
                  style="width: 100%;"
                  class="content-table"
              >
                <el-table-column prop="eventName" label="事件名称" min-width="150"></el-table-column>
                <el-table-column prop="eventType" label="事件类型" min-width="120">
                  <template #default="scope">
                    {{ eventTypeMap[scope.row.eventType] || '未知' }}
                  </template>
                </el-table-column>
                <el-table-column prop="startTime" label="开始时间" min-width="160"></el-table-column>
                <el-table-column prop="priority" label="优先级" min-width="80"></el-table-column>
                <el-table-column label="操作" min-width="100">
                  <template #default="scope">
                    <el-button size="mini" type="danger" @click="deleteEvent(termIndex, scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div v-else class="empty-state inside-module">
                <div class="empty-icon">⏳</div>
                <p class="empty-text">暂无事件，点击"添加事件"按钮创建</p>
              </div>
            </div>

            <!-- 模块3：事件添加表单 -->
            <div class="event-form-container" v-if="term.isAddingEvent">
              <el-form
                  :ref="(el) => { if (el) eventFormRefs[termIndex] = el; }"
                  :model="eventForms[termIndex]"
                  :rules="eventFormRules"
                  label-width="120px"
                  size="mini"
                  class="form-content event-form"
              >
                <el-form-item label="事件名称" prop="eventName">
                  <el-input
                      v-model="eventForms[termIndex].eventName"
                      placeholder="请输入事件名称"
                      maxlength="100"
                      class="form-input"
                  ></el-input>
                </el-form-item>

                <el-form-item label="事件类型" prop="eventType">
                  <el-select v-model="eventForms[termIndex].eventType" placeholder="请选择事件类型" class="form-input">
                    <el-option label="选课开始" :value="1"></el-option>
                    <el-option label="选课截止" :value="2"></el-option>
                    <el-option label="成绩录入开始" :value="3"></el-option>
                    <el-option label="成绩截止" :value="4"></el-option>
                    <el-option label="考试" :value="5"></el-option>
                    <el-option label="假期" :value="6"></el-option>
                    <el-option label="会议" :value="7"></el-option>
                    <el-option label="其他" :value="8"></el-option>
                  </el-select>
                </el-form-item>

                <el-row :gutter="20" class="form-row">
                  <el-col :span="12">
                    <el-form-item label="开始时间" prop="startTime">
                      <el-date-picker
                          v-model="eventForms[termIndex].startTime"
                          type="datetime"
                          placeholder="选择开始时间"
                          format="YYYY-MM-DD HH:mm"
                          value-format="YYYY-MM-DD HH:mm"
                          :disabled-date="(date) => disableEventDate(date, termIndex, 'start')"
                          class="form-input"
                      ></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="结束时间" prop="endTime">
                      <el-date-picker
                          v-model="eventForms[termIndex].endTime"
                          type="datetime"
                          placeholder="选择结束时间"
                          format="YYYY-MM-DD HH:mm"
                          value-format="YYYY-MM-DD HH:mm"
                          :disabled-date="(date) => disableEventDate(date, termIndex, 'end')"
                          class="form-input"
                      ></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20" class="form-row">
                  <el-col :span="12">
                    <el-form-item label="是否启用" prop="isActive">
                      <el-switch
                          v-model="eventForms[termIndex].isActive"
                          active-text="启用"
                          inactive-text="禁用"
                      ></el-switch>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="优先级" prop="priority">
                      <el-input-number
                          v-model="eventForms[termIndex].priority"
                          :min="1"
                          :max="10"
                          :step="1"
                          placeholder="1-10"
                          class="form-input"
                      ></el-input-number>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item label="提前通知(天)" prop="notifyBeforeDays">
                  <el-input-number
                      v-model="eventForms[termIndex].notifyBeforeDays"
                      :min="-30"
                      :max="30"
                      :step="1"
                      placeholder="如-7表示提前7天"
                      class="form-input"
                  ></el-input-number>
                </el-form-item>

                <el-form-item label="描述（可选）">
                  <el-input
                      v-model="eventForms[termIndex].description"
                      type="textarea"
                      rows="2"
                      placeholder="请输入事件描述"
                      maxlength="500"
                      class="form-input"
                  ></el-input>
                </el-form-item>

                <el-form-item class="form-buttons">
                  <el-button size="small" @click="resetEventForm(termIndex)">重置</el-button>
                  <el-button size="small" type="primary" @click="() => addEventToTerm(termIndex)" :loading="eventLoading[termIndex]">
                    提交事件
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>

        <!-- 底部操作按钮 -->
        <div class="step-navigation" v-if="Array.isArray(currentYearTerms) && currentYearTerms.length > 0">
          <el-button @click="prevStep">返回修改学期</el-button>
          <el-button type="primary" @click="completeAll" :loading="submitLoading">完成所有操作并保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, nextTick, reactive, type Ref, watch } from 'vue';
import TCalendar from './TCalendar.vue';
import { clockFactory } from './utils';
import { listYear, addYearTermEvent } from "@/api/course/year"; //@ts-ignore
import { listTerm } from "@/api/course/term"; //@ts-ignore
import { listEvents } from "@/api/course/events"; //@ts-ignore
import  {loadAllParams} from "@/api/page";
import {
  ElTable, ElTableColumn, ElButton, ElForm, ElFormItem,
  ElInput, ElDatePicker, ElInputNumber, ElSelect, ElOption,
  ElSwitch, ElMessage, ElLoading, ElMessageBox
} from 'element-plus';

// -------------------------- 类型定义 --------------------------
interface TermType {
  id: string;
  termCode: string;
  termName: string;
  startDate: string;
  endDate: string;
  semesterNum: number;
  calendarStartWeek: string;
  status: string;
  yearId: string;
  yearCode: string;
  yearName: string;
  events: Ref<EventType[]>;
  isAddingEvent: boolean;
}

interface EventType {
  id: string;
  eventName: string;
  eventType: number;
  startTime: string;
  endTime: string;
  isActive: boolean;
  priority: number;
  notifyBeforeDays: number;
  description: string;
  termId: string;
  termCode: string;
  termName: string;
}

// -------------------------- 核心状态：控制新增流程 --------------------------
const isInAddingFlow = ref<boolean>(false);
const currentStep = ref<number>(1);
const stepLoading = ref<boolean>(false);
const addTermLoading = ref<boolean>(false);
const submitLoading = ref<boolean>(false);
const eventLoading = ref<Record<number, boolean>>({});

// -------------------------- 数据定义 --------------------------
// 事件类型字典
const eventTypeMap = {
  1: '选课开始',
  2: '选课截止',
  3: '成绩录入开始',
  4: '成绩截止',
  5: '考试',
  6: '假期',
  7: '会议',
  8: '其他'
};

// 列表数据
const yearInfo = ref<any[]>([]);
const yearInfoLoaded = ref<boolean>(false);
const sanitizedYearInfo = computed(() => formatData(yearInfo.value));

const termInfo = ref<any[]>([]);
const termInfoLoaded = ref<boolean>(false);
const sanitizedTermInfo = computed(() => formatData(termInfo.value));

const eventsInfo = ref<any[]>([]);
const eventsInfoLoaded = ref<boolean>(false);

// 新增流程临时数据
const currentYear = ref<any>(null);
const currentYearTerms = ref<TermType[]>([]);
const selectedTermIds = ref<string[]>([]);

// 每个学期的事件表单数据和ref
const eventForms = ref<(Record<string, any>)[]>([]);
const eventFormRefs = ref<(InstanceType<typeof ElForm> | null)[]>([]);

// 表单数据
const yearForm = reactive({
  yearName: '',
  yearCode: '',
  startDate: '',
  endDate: '',
  semesterNum: 2,
  status: '0',
  isDefault: false,
  remark: ''
});

const termForm = reactive({
  termName: '',
  termCode: '',
  startDate: '',
  endDate: '',
  semesterNum: 18,
  calendarStartWeek: '',
  status: '0',
  yearId: '',
  yearCode: ''
});

// 表单验证规则
const yearFormRules = reactive({
  yearName: [{ required: true, message: '请输入学年名称', trigger: 'blur' }],
  yearCode: [{ required: true, message: '请输入学年代码', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择起始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  semesterNum: [{ required: true, message: '请输入学期数', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
});

const termFormRules = reactive({
  termName: [{ required: true, message: '请输入学期名称', trigger: 'blur' }],
  termCode: [{ required: true, message: '请输入学期代码', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择起始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  semesterNum: [{ required: true, message: '请输入教学周数', trigger: 'blur' }],
  calendarStartWeek: [{ required: true, message: '请选择校历第1周起始日期', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
});

const eventFormRules = reactive({
  eventName: [{ required: true, message: '请输入事件名称', trigger: 'blur' }],
  eventType: [
    { required: true, message: '请选择事件类型', trigger: 'change' },
    { type: 'number', message: '事件类型必须为数字', trigger: 'change' }
  ],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'blur' },
    { type: 'number', min: 1, max: 10, message: '优先级必须是1-10之间的数字', trigger: 'blur' }
  ],
  notifyBeforeDays: [
    { type: 'number', min: -30, max: 30, message: '提前通知天数必须是-30到30之间的数字', trigger: 'blur' }
  ]
});

// 表单引用
const yearFormRef = ref<InstanceType<typeof ElForm> | null>(null);
const termFormRef = ref<InstanceType<typeof ElForm> | null>(null);

// 日历状态
const currentDate = new Date();
const startYear = ref(currentDate.getFullYear());
const startMonth = ref(currentDate.getMonth() + 1);
const minYear = ref(2000);
const minMonth = ref(1);
const maxYear = ref(2100);
const maxMonth = ref(12);
const isReset = ref(false);

// 学期颜色映射
const termColors = [
  '#409eff', // 蓝色
  '#52c41a', // 绿色
  '#faad14', // 黄色
  '#f5222d', // 红色
  '#722ed1', // 紫色
  '#1890ff', // 亮蓝
  '#ff7a45', // 橙色
  '#00b42a'  // 深绿
];

const termColorMap = computed(() => {
  const map: Record<string, string> = {};
  if (Array.isArray(termInfo.value)) {
    termInfo.value.forEach((term, index) => {
      map[term.id] = termColors[index % termColors.length];
    });
  }
  return map;
});

// -------------------------- 日历逻辑 --------------------------
const displayedMonths = computed(() => {
  return Array.from({ length: 6 }, (_, i) => {
    let calcYear = startYear.value;
    let calcMonth = startMonth.value + i;
    if (calcMonth > 12) {
      calcYear += 1;
      calcMonth -= 12;
    }
    if (calcMonth < 1) {
      calcYear -= 1;
      calcMonth += 12;
    }
    return {
      year: calcYear,
      month: calcMonth,
      calendarTime: `${calcYear}-${clockFactory(calcMonth)}-01`,
      key: `${calcYear}-${calcMonth}`
    };
  });
});

const displayMonthRange = computed(() => {
  const [first, last] = [displayedMonths.value[0], displayedMonths.value[5]];
  return first.year !== last.year
      ? `${first.year}年${first.month}月-${last.year}年${last.month}月`
      : `${first.month}-${last.month}月`;
});

const displayYear = computed(() => displayedMonths.value[0].year);
const isMinMonth = computed(() => {
  const first = displayedMonths.value[0];
  return first.year <= minYear.value && first.month <= minMonth.value;
});
const isMaxMonth = computed(() => {
  const last = displayedMonths.value[5];
  return last.year >= maxYear.value && last.month >= maxMonth.value;
});

function changeMonth(step: number) {
  startMonth.value += step;
  if (startMonth.value > 12) {
    startYear.value += 1;
    startMonth.value = 1;
  }
  if (startMonth.value < 1) {
    startYear.value -= 1;
    startMonth.value = 12;
  }
  isReset.value = !isReset.value;
}

function resetToCurrent() {
  const now = new Date();
  startYear.value = now.getFullYear();
  startMonth.value = now.getMonth() + 1;
  isReset.value = !isReset.value;
}

// 获取当前月需要标记的学期日期
const getMonthTermMarks = (year: number, month: number) => {
  if (!Array.isArray(termInfo.value) || termInfo.value.length === 0) {
    console.log(`获取 ${year}年${month}月标记：无学期数据`);
    return [];
  }

  const result = termInfo.value.flatMap(term => {
    // 跳过日期无效的学期
    if (!term.startDate || !term.endDate) return [];

    const start = new Date(term.startDate);
    const end = new Date(term.endDate);

    // 验证日期对象有效性
    if (isNaN(start.getTime()) || isNaN(end.getTime())) {
      console.warn(`学期 ${term.termName} 日期无效：`, term.startDate, term.endDate);
      return [];
    }

    const marks = [];
    // 检查开始日期是否在当前月
    if (start.getFullYear() === year && start.getMonth() + 1 === month) {
      marks.push({
        date: term.startDate,
        type: 'start',
        termId: term.id,
        color: termColorMap.value[term.id] || '#409eff'
      });
      console.log(`添加开始标记：${term.startDate}（${term.termName}）`);
    }

    // 检查结束日期是否在当前月
    if (end.getFullYear() === year && end.getMonth() + 1 === month) {
      marks.push({
        date: term.endDate,
        type: 'end',
        termId: term.id,
        color: termColorMap.value[term.id] || '#409eff'
      });
      console.log(`添加结束标记：${term.endDate}（${term.termName}）`);
    }

    return marks;
  });

  console.log(`获取 ${year}年${month}月标记：`, result);
  return result;
};

// -------------------------- 新增流程控制方法 --------------------------
function startAddingFlow() {
  isInAddingFlow.value = true;
  currentStep.value = 1;
  resetYearForm();
  currentYear.value = null;
  currentYearTerms.value = [];
  selectedTermIds.value = [];
  eventForms.value = [];
  eventFormRefs.value = [];
  eventLoading.value = {};
}

function startAddingFlowFromTerm() {
  ElMessage.warning('请先通过"新增学年计划"完成学年添加后，再批量添加学期');
}

function startAddingFlowFromEvent() {
  ElMessage.warning('请先通过"新增学年计划"完成学年和学期添加后，再添加事件');
}

function addTermsForYear(year: any) {
  if (!year) return;
  currentYear.value = year;
  isInAddingFlow.value = true;
  currentStep.value = 2;

  const filteredTerms = Array.isArray(termInfo.value)
      ? termInfo.value.filter((term: any) => term.yearCode === year.yearCode)
      : [];

  currentYearTerms.value = filteredTerms.map((term: any, index: number) => ({
    id: term.id || `term_${year.yearCode}_${index}`,
    termCode: term.termCode || '',
    termName: term.termName || '',
    startDate: term.startDate || '',
    endDate: term.endDate || '',
    semesterNum: term.semesterNum || 0,
    calendarStartWeek: term.calendarStartWeek || '',
    status: term.status || '0',
    yearId: term.yearId || year.id || '',
    yearCode: term.yearCode || year.yearCode || '',
    yearName: term.yearName || year.yearName || '',
    events: ref<EventType[]>(Array.isArray(term.events) ? term.events : []),
    isAddingEvent: false
  }));

  resetTermForm();
  initEventForms();
}

function addEventsForTerm(term: any) {
  if (!term) return;
  currentYear.value = {
    yearName: term.yearName || '',
    yearCode: term.yearCode || '',
    id: term.yearId || `year_${term.yearCode}`
  };

  currentYearTerms.value = [{
    ...term,
    id: term.id || `term_${Date.now()}`,
    events: ref<EventType[]>(
        Array.isArray(eventsInfo.value)
            ? eventsInfo.value.filter((event: any) => event.termId === term.id)
            : []
    ),
    isAddingEvent: true
  }];

  initEventForms();
  isInAddingFlow.value = true;
  currentStep.value = 3;
}

function editYear(year: any) {
  if (!year) return;
  currentYear.value = year;
  yearForm.yearName = year.yearName || '';
  yearForm.yearCode = year.yearCode || '';
  yearForm.startDate = year.startDate || '';
  yearForm.endDate = year.endDate || '';
  yearForm.semesterNum = year.semesterNum || 2;
  yearForm.status = year.status || '0';
  yearForm.isDefault = year.isDefault || false;
  yearForm.remark = year.remark || '';

  isInAddingFlow.value = true;
  currentStep.value = 1;
  currentYearTerms.value = [];
}

function cancelAddingFlow() {
  isInAddingFlow.value = false;
  currentStep.value = 1;
  currentYear.value = null;
  currentYearTerms.value = [];
  selectedTermIds.value = [];
  eventForms.value = [];
  eventFormRefs.value = [];
  eventLoading.value = {};
  resetYearForm();
  resetTermForm();
}

async function nextStep() {
  stepLoading.value = true;
  try {
    if (currentStep.value === 1) {
      if (!yearFormRef.value) return;
      await yearFormRef.value.validate();

      if (!yearForm.startDate || !yearForm.endDate || new Date(yearForm.startDate) > new Date(yearForm.endDate)) {
        ElMessage.warning('结束日期不能早于起始日期');
        return;
      }

      currentYear.value = {
        ...yearForm,
        id: currentYear.value?.id || `year_${Date.now()}`
      };
      currentYearTerms.value = [];
      currentStep.value = 2;
      resetTermForm();
    } else if (currentStep.value === 2) {
      if (!Array.isArray(currentYearTerms.value)) {
        currentYearTerms.value = [];
        ElMessage.error('学期数据格式错误，请重新添加');
        return;
      }
      if (currentYearTerms.value.length === 0) {
        ElMessage.error('请先添加至少一个学期');
        return;
      }
      const invalidTerm = currentYearTerms.value.find(term =>
          !term.id || !term.termName || !term.startDate || !term.endDate
      );
      if (invalidTerm) {
        ElMessage.error('存在无效学期（缺少名称/日期），请删除后重新添加');
        return;
      }

      currentStep.value = 3;
      await nextTick();
      const initSuccess = initEventForms();
      if (!initSuccess) {
        currentStep.value = 2;
        ElMessage.error('事件表单初始化失败，请重试');
        return;
      }
    }
  } catch (error) {
    console.error('下一步失败：', error);
    ElMessage.error('操作失败，请重试');
  } finally {
    setTimeout(() => {
      stepLoading.value = false;
    }, 300);
  }
}

function prevStep() {
  stepLoading.value = true;
  if (currentStep.value === 2) {
    currentStep.value = 1;
  } else if (currentStep.value === 3) {
    currentStep.value = 2;
  }
  setTimeout(() => {
    stepLoading.value = false;
  }, 300);
}

// -------------------------- 学期操作方法 --------------------------
async function addTerm() {
  addTermLoading.value = true;
  if (!termFormRef.value || !currentYear.value) {
    addTermLoading.value = false;
    return;
  }

  try {
    await termFormRef.value.validate();

    if (!termForm.startDate || !termForm.endDate || new Date(termForm.startDate) > new Date(termForm.endDate)) {
      ElMessage.warning('结束日期不能早于起始日期');
      return;
    }
    if (!termForm.calendarStartWeek || new Date(termForm.calendarStartWeek) < new Date(termForm.startDate) ||
        new Date(termForm.calendarStartWeek) > new Date(termForm.endDate)) {
      ElMessage.warning('校历第1周起始日期必须在学期日期范围内');
      return;
    }
    if (new Date(termForm.startDate) < new Date(currentYear.value.startDate) ||
        new Date(termForm.endDate) > new Date(currentYear.value.endDate)) {
      ElMessage.warning('学期日期必须在学年日期范围内');
      return;
    }

    const newTerm: TermType = {
      ...termForm,
      yearId: currentYear.value.id || '',
      yearCode: currentYear.value.yearCode || '',
      yearName: currentYear.value.yearName || '',
      id: `term_${Date.now()}`,
      events: ref<EventType[]>([]),
      isAddingEvent: false
    };

    if (currentYearTerms.value.some(term => term.termCode === newTerm.termCode)) {
      ElMessage.warning('学期代码已存在，请修改');
      return;
    }

    currentYearTerms.value.push(newTerm);
    ElMessage.success('学期添加成功');
    initEventForms();
    resetTermForm();

  } catch (error) {
    console.error('添加学期失败：', error);
    ElMessage.error('表单填写有误，请检查后重试');
  } finally {
    addTermLoading.value = false;
  }
}

function removeTerm(index: number) {
  if (index < 0 || index >= currentYearTerms.value.length) return;
  currentYearTerms.value.splice(index, 1);
  initEventForms();
  ElMessage.success('学期删除成功');
}

function batchDeleteTerms() {
  if (selectedTermIds.value.length === 0) return;
  ElMessageBox.confirm('确定要删除选中的学期吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    currentYearTerms.value = currentYearTerms.value.filter(term => !selectedTermIds.value.includes(term.id));
    selectedTermIds.value = [];
    initEventForms();
    ElMessage.success('选中学期已删除');
  });
}

function handleTermSelectionChange(selection: TermType[]) {
  selectedTermIds.value = selection.map(term => term.id);
}



// 日期禁用逻辑 - 学期开始日期
function disableTermStartDate(date: Date) {
  if (!currentYear.value || !currentYear.value.startDate || !currentYear.value.endDate) return false;
  const yearStart = new Date(currentYear.value.startDate);
  const yearEnd = new Date(currentYear.value.endDate);

  // 设置时间为当天开始，避免时间部分影响比较
  yearStart.setHours(0, 0, 0, 0);
  yearEnd.setHours(0, 0, 0, 0);

  // 允许在学年日期范围内选择，包括边界日期
  // 修改为 date < yearStart 而不是 date <= yearStart，允许选择学年开始日期
  if (date < yearStart || date >= yearEnd) return true;

  // 检查是否与其他学期日期冲突
  return currentYearTerms.value.some(term => {
    if (!term.startDate || !term.endDate) return false;
    const termStart = new Date(term.startDate);
    const termEnd = new Date(term.endDate);
    // 检查日期是否在已有学期的范围内
    return date >= termStart && date <= termEnd;
  });
}


// 日期禁用逻辑 - 学期结束日期
function disableTermEndDate(date: Date) {
  if (!currentYear.value || !currentYear.value.startDate || !currentYear.value.endDate || !termForm.startDate) return false;
  const termStart = new Date(termForm.startDate);
  const yearEnd = new Date(currentYear.value.endDate);

  if (date <= termStart || date >= yearEnd) return true;

  return currentYearTerms.value.some(term => {
    const existingStart = new Date(term.startDate);
    const existingEnd = new Date(term.endDate);
    return date >= existingStart && date <= existingEnd;
  });
}

// 日期禁用逻辑 - 校历第1周开始日期
function disableCalendarStartDate(date: Date) {
  if (!termForm.startDate || !termForm.endDate) return false;
  const termStart = new Date(termForm.startDate);
  const termEnd = new Date(termForm.endDate);

  // 设置时间为当天开始，避免时间部分影响比较
  termStart.setHours(0, 0, 0, 0);
  termEnd.setHours(0, 0, 0, 0);
  date.setHours(0, 0, 0, 0);

  // 允许在学期日期范围内选择，包括边界日期
  return date < termStart || date > termEnd;
}



// -------------------------- 事件操作方法 --------------------------
function initEventForms(): boolean {
  try {
    eventForms.value = [];
    eventFormRefs.value = [];
    eventLoading.value = {};

    if (!Array.isArray(currentYearTerms.value) || currentYearTerms.value.length === 0) {
      console.error('事件表单初始化失败：无有效学期');
      return false;
    }

    currentYearTerms.value.forEach((_, index) => {
      eventForms.value[index] = {
        eventName: '',
        eventType: 1,
        startTime: '',
        endTime: '',
        isActive: true,
        priority: 5,
        notifyBeforeDays: -7,
        description: ''
      };
      eventLoading.value[index] = false;
      eventFormRefs.value[index] = null;
    });

    return true;
  } catch (error) {
    console.error('初始化事件表单失败：', error);
    return false;
  }
}

watch(currentYearTerms, (newTerms) => {
  if (Array.isArray(newTerms) && newTerms.length > 0 && currentStep.value === 3) {
    nextTick(() => {
      initEventForms();
    });
  }
}, { deep: true });

async function toggleEventForm(termIndex: number) {
  if (termIndex < 0 || termIndex >= currentYearTerms.value.length) return;

  currentYearTerms.value.forEach((term, idx) => {
    term.isAddingEvent = idx === termIndex;
  });

  await nextTick();

  if (!eventFormRefs.value[termIndex]) {
    console.warn(`学期 ${termIndex + 1} 表单ref未初始化，尝试重新绑定`);
    ElMessage.warning('表单加载中，请稍候...');
    setTimeout(() => {
      if (!eventFormRefs.value[termIndex]) {
        ElMessage.error('表单加载失败，请再次点击"添加事件"');
      }
    }, 100);
  }
}

async function addEventToTerm(termIndex: number) {
  if (termIndex < 0 || termIndex >= currentYearTerms.value.length) {
    ElMessage.error('无效的学期索引');
    return;
  }

  eventLoading.value[termIndex] = true;
  const term = currentYearTerms.value[termIndex];
  let formData = eventForms.value[termIndex];

  if (!term) {
    eventLoading.value[termIndex] = false;
    ElMessage.error('学期数据缺失');
    return;
  }

  // 初始化events
  if (!term.events) {
    term.events = ref<EventType[]>([]);
  } else {
    try {
      const _ = term.events.value;
    } catch (e) {
      term.events = ref<EventType[]>(Array.isArray(term.events) ? term.events : []);
    }
    if (!Array.isArray(term.events.value)) {
      term.events.value = [];
    }
  }

  if (!formData) {
    formData = {};
    eventForms.value[termIndex] = formData;
  }

  try {
    const defaultFormData = {
      eventName: formData.eventName || '未命名事件',
      eventType: formData.eventType || 8,
      startTime: formData.startTime || `${term.startDate} 00:00`,
      endTime: formData.endTime || `${term.endDate} 23:59`,
      isActive: formData.isActive !== undefined ? formData.isActive : true,
      priority: formData.priority || 5,
      notifyBeforeDays: formData.notifyBeforeDays || 0,
      description: formData.description || ''
    };

    // 时间验证
    if (new Date(defaultFormData.startTime) > new Date(defaultFormData.endTime)) {
      ElMessage.warning('结束时间不能早于开始时间，已自动调整为学期结束时间');
      defaultFormData.endTime = `${term.endDate} 23:59`;
    }
    if (new Date(defaultFormData.startTime) < new Date(term.startDate)+1) {
      ElMessage.warning('开始时间早于学期起始时间，已自动调整为学期起始时间');
      defaultFormData.startTime = `${term.startDate} 00:00`;
    }
    if (new Date(defaultFormData.endTime) >=new Date(term.endDate)) {
      ElMessage.warning('结束时间晚于学期结束时间，已自动调整为学期结束时间');
      defaultFormData.endTime = `${term.endDate} 23:59`;
    }

    const newEvent: EventType = {
      id: `event_${Date.now()}`,
      ...defaultFormData,
      termId: term.id,
      termCode: term.termCode || '',
      termName: term.termName || '未命名学期'
    };

    term.events.value.push(newEvent);

    const missingFields: string[] = [];
    if (!formData.eventName) missingFields.push('事件名称');
    if (!formData.eventType) missingFields.push('事件类型');
    if (!formData.startTime) missingFields.push('开始时间');
    if (!formData.endTime) missingFields.push('结束时间');
    if (!formData.priority) missingFields.push('优先级');

    if (missingFields.length > 0) {
      ElMessage.success(`强制提交成功！以下字段使用默认值：${missingFields.join('、')}`);
    } else {
      ElMessage.success(`已为${term.termName || '未命名学期'}添加事件`);
    }

    resetEventForm(termIndex);
    term.isAddingEvent = false;

  } catch (error) {
    console.error('添加事件失败：', error);
    ElMessage.error('强制提交失败，请重试');
  } finally {
    eventLoading.value[termIndex] = false;
  }
}


function deleteEvent(termIndex: number, eventIndex: number) {
  if (termIndex < 0 || termIndex >= currentYearTerms.value.length) return;
  const term = currentYearTerms.value[termIndex];
  if (!term.events || eventIndex < 0 || eventIndex >= term.events.value.length) return;

  term.events.value.splice(eventIndex, 1);
  ElMessage.success(`已删除${term.termName || '未命名学期'}的事件`);
}

function disableEventDate(date: Date, termIndex: number, type: 'start' | 'end') {
  if (termIndex < 0 || termIndex >= currentYearTerms.value.length) return false;
  const term = currentYearTerms.value[termIndex];
  const formData = eventForms.value[termIndex];

  if (!term || !term.startDate || !term.endDate) return false;

  const termStartDate = new Date(term.startDate);
  const termEndDate = new Date(term.endDate);

  // 设置时间为当天开始，避免时间部分影响比较
  termStartDate.setHours(0, 0, 0, 0);
  termEndDate.setHours(0, 0, 0, 0);

  // 允许在学期日期范围内选择，包括边界日期
  if (date < termStartDate || date > termEndDate) {  // 注意这里是 date > termEndDate，不包含结束日期
    return true;
  }

  if (type === 'end' && formData?.startTime) {
    return date < new Date(formData.startTime);
  }

  return false;
}


// -------------------------- 表单重置方法 --------------------------
function resetYearForm() {
  if (yearFormRef.value) {
    yearFormRef.value.resetFields();
  }
  yearForm.semesterNum = 2;
  yearForm.status = '0';
  yearForm.isDefault = false;
}

function resetTermForm() {
  if (termFormRef.value) {
    termFormRef.value.resetFields();
  }
  termForm.semesterNum = 18;
  termForm.status = '0';
  termForm.yearCode = currentYear.value ? currentYear.value.yearCode : '';
  termForm.yearId = currentYear.value ? currentYear.value.id : '';
}

function resetEventForm(termIndex: number) {
  if (termIndex < 0 || termIndex >= eventFormRefs.value.length) return;
  const formRef = eventFormRefs.value[termIndex];
  if (formRef) {
    formRef.resetFields();
  }
  eventForms.value[termIndex] = {
    eventName: '',
    eventType: 1,
    startTime: '',
    endTime: '',
    isActive: true,
    priority: 5,
    notifyBeforeDays: -7,
    description: ''
  };
}

// -------------------------- 数据处理与接口调用 --------------------------
function formatData(data: any[]) {
  return (Array.isArray(data) ? data : []).map(item => {
    const sanitized = { ...item };
    Object.keys(sanitized).forEach(key => {
      const value = sanitized[key];
      if (typeof value === 'string') {
        sanitized[key] = value.replace(/<!--.*?-->|<\/?[^>]+>/g, '');
      }
    });
    return sanitized;
  });
}

function formatStatus(_: any, __: any, cellValue: number | string) {
  const statusMap = {
    0: '未开始',
    1: '进行中',
    2: '已结束',
    '0': '未开始',
    '1': '进行中',
    '2': '已结束'
  };
  return statusMap[cellValue as keyof typeof statusMap] || '未知';
}

function formatBoolean(_: any, __: any, cellValue: boolean | number) {
  return cellValue === true || cellValue === 1 ? '是' : '否';
}

const getAllYearList = async () => {
  try {
    const res = await listYear();
    console.log('原始学年接口数据：', res);
    yearInfo.value = res?.code === 200 && Array.isArray(res.rows)
        ? res.rows.map(row => ({ ...row, yearName: row.yearName || row.yearCode }))
        : [];
  } catch (e) {
    console.error('获取学年失败：', e);
    yearInfo.value = [];
  } finally {
    yearInfoLoaded.value = true;
  }
};

const getAllTermList = async () => {
  try {
    // 同时获取学期和学年数据，确保数据一致性
    const [termRes, yearRes] = await Promise.all([listTerm(), listYear()]);

    // 处理学年数据
    let yearData = [];
    if (yearRes?.code === 200 && Array.isArray(yearRes.rows)) {
      yearData = yearRes.rows.map(row => ({
        ...row,
        yearName: row.yearName || row.yearCode
      }));
      console.log('获取到的学年数据：', yearData);
    }

    if (termRes?.code === 200 && Array.isArray(termRes.rows)) {
      termInfo.value = termRes.rows.map(row => {
        // 确保startDate和endDate存在且格式正确
        const startDate = row.startDate ? new Date(row.startDate) : null;
        const endDate = row.endDate ? new Date(row.endDate) : null;

        // 验证日期有效性
        const isValidStartDate = startDate && !isNaN(startDate.getTime());
        const isValidEndDate = endDate && !isNaN(endDate.getTime());

        // 通过yearId匹配学年数据
        const year = yearData.find((y: any) => y.id === row.yearId);

        return {
          ...row,
          termName: row.termName || row.termCode,
          yearName: year ? year.yearName : '未知学年', // 找不到对应学年则显示"未知学年"
          id: row.id || `term_${row.termCode}`,
          // 确保日期格式标准化
          startDate: isValidStartDate ? row.startDate : null,
          endDate: isValidEndDate ? row.endDate : null
        };
      });
      console.log('处理后的学期数据：', termInfo.value);
    } else {
      termInfo.value = [];
      console.warn('学期接口返回格式不正确');
    }
  } catch (e) {
    console.error('获取学期失败：', e);
    termInfo.value = [];
  } finally {
    termInfoLoaded.value = true;
  }
};


watch(
    () => termInfoLoaded.value,
    (isTermLoaded) => {
      if (isTermLoaded) {
        // 切换 isReset 的值，触发子组件重新计算标记
        isReset.value = !isReset.value;
      }
    }
);
const getAllEventsList = async () => {
  try {
    const res = await listEvents(loadAllParams);
    console.log('原始事件接口数据res：', res);

    if (res?.code === 200 && Array.isArray(res.rows)) {
      // 先获取所有学期列表
      const termListResponse = await listTerm(loadAllParams);
      let termList = [];
      if (termListResponse?.code === 200 && Array.isArray(termListResponse.rows)) {
        termList = termListResponse.rows;
      }

      // 通过termId在学期列表中匹配获取termName
      const eventsWithTermName = res.rows.map((event: any) => {
        // 在学期列表中查找匹配的学期
        const matchedTerm = termList.find((term: any) => term.id === event.termId);
        const termName = matchedTerm ? matchedTerm.termName : '未知学期';

        return {
          ...event,
          termName: termName,
          isActive: event.isActive === 1
        };
      });

      eventsInfo.value = eventsWithTermName;
    } else {
      eventsInfo.value = [];
    }
  } catch (e) {
    console.error('获取事件失败：', e);
    eventsInfo.value = [];
  } finally {
    eventsInfoLoaded.value = true;
  }
};




async function completeAll() {
  submitLoading.value = true;
  if (!currentYear.value || !Array.isArray(currentYearTerms.value) || currentYearTerms.value.length === 0) {
    ElMessage.warning('请先添加学年和学期');
    submitLoading.value = false;
    return;
  }

  const loading = ElLoading.service({
    lock: true,
    text: '正在保存所有数据...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {
    const yearVo = {
      year: {
        id: currentYear.value.id,
        yearName: currentYear.value.yearName || '',
        yearCode: currentYear.value.yearCode || '',
        startDate: currentYear.value.startDate ? `${currentYear.value.startDate} 00:00:00` : '',
        endDate: currentYear.value.endDate ? `${currentYear.value.endDate} 23:59:59` : '',
        semesterNum: currentYearTerms.value.length,
        status: currentYear.value.status || '0',
        isDefault: currentYear.value.isDefault ? 1 : 0,
        remark: currentYear.value.remark || ''
      },
      terms: currentYearTerms.value.map(term => ({
        term: {
          id: term.id,
          termName: term.termName || '',
          termCode: term.termCode || '',
          startDate: term.startDate ? `${term.startDate} 00:00:00` : '',
          endDate: term.endDate ? `${term.endDate} 23:59:59` : '',
          semesterNum: term.semesterNum || 0,
          calendarStartWeek: term.calendarStartWeek ? `${term.calendarStartWeek} 00:00:00` : '',
          status: term.status || '0'
        },
        events: (term.events?.value || []).map(event => ({
          eventName: event.eventName || '',
          eventType: event.eventType || 8,
          startTime: event.startTime || '',
          endTime: event.endTime || '',
          isActive: event.isActive ? 1 : 0,
          priority: event.priority || 5,
          notifyBeforeDays: event.notifyBeforeDays || 0,
          description: event.description || ''
        }))
      }))
    };

    const response = await addYearTermEvent(yearVo);
    if (response?.code === 200) {
      ElMessage.success('学年、所有学期及事件均保存成功！');
      cancelAddingFlow();
      await getAllYearList();
      await getAllTermList();
      await getAllEventsList();
    } else {
      ElMessage.error('保存失败: ' + (response?.msg || '未知错误'));
    }
  } catch (error) {
    console.error('提交数据失败：', error);
    ElMessage.error('保存失败：' + (error.message || '网络异常'));
  } finally {
    loading.close();
    submitLoading.value = false;
  }
}

// -------------------------- 生命周期 --------------------------
onMounted(async () => {
  await Promise.all([getAllYearList(), getAllTermList()]);
  await getAllEventsList();
});
</script>

<style scoped lang="less">
// 基础变量定义
@light-line: #ebeef5;
@primary-color: #409eff;
@secondary-color: #f5f7fa;
@text-primary: #333;
@text-secondary: #666;
@text-placeholder: #999;
@spacing-xs: 4px;
@spacing-sm: 8px;
@spacing-md: 16px;
@spacing-lg: 24px;
@border-radius: 6px;
@shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.06);
@shadow-md: 0 4px 12px rgba(0, 0, 0, 0.08);

// 全局容器样式
.calendar-wrapper {
  width: 100%;
  min-height: 100vh;
  padding: @spacing-md;
  box-sizing: border-box;
  background-color: #f8f9fa;
}

// 头部控制栏样式
.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: @spacing-sm @spacing-md;
  margin-bottom: @spacing-md;
  background-color: #fff;
  border-radius: @border-radius;
  box-shadow: @shadow-sm;

  .header-left {
    .date-range {
      font-size: 1.1rem;
      color: @text-primary;
      font-weight: 500;
    }
  }

  .header-right {
    display: flex;
    gap: @spacing-sm;

    :deep(.el-button) {
      font-size: 0.9rem;
      padding: 0 12px;
      height: 32px;
      transition: all 0.2s;

      &:hover {
        transform: translateY(-1px);
        box-shadow: @shadow-sm;
      }
    }
  }
}

// 多日历容器样式（优化为一行展示）
.multi-month-container {
  display: flex;
  gap: 8px; // 缩小间距
  overflow-x: hidden; // 禁用横向滚动
  padding: 8px 0;
  margin-bottom: @spacing-md;
  width: 100%;
  box-sizing: border-box;

  // 单个日历卡片：按比例分配宽度
  .single-month-card {
    flex: 1; // 关键：6个卡片等分宽度
    min-width: calc((100% - 40px) / 6); // 计算最小宽度（总间距8px*5=40px）
    max-width: calc((100% - 40px) / 6); // 固定最大宽度
    background-color: #fff;
    border-radius: @border-radius;
    box-shadow: @shadow-sm;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      box-shadow: @shadow-md;
      transform: translateY(-2px);
    }

    .month-title {
      text-align: center;
      padding: 6px 0; // 缩小内边距
      font-size: 0.85rem; // 缩小字体
      color: @text-primary;
      font-weight: 500;
      border-bottom: 1px solid @light-line;
    }

    .compact-calendar {
      :deep(.t-calendar) {
        width: 100% !important;
        height: 220px !important; // 固定日历高度
      }

      // 周头样式
      :deep(.week-header) {
        height: 30px !important;

        > div {
          line-height: 30px !important;
          font-size: 0.75rem !important;
        }
      }

      // 日期格子样式
      :deep(.calendar-grid) {
        padding: 4px 0 !important;

        > div {
          height: 26px !important;
          line-height: 26px !important;
          font-size: 0.75rem !important;
          margin: 1px 0 !important;
          transition: all 0.2s;

          &:hover {
            background-color: rgba(64, 158, 255, 0.1);
          }

          &.active {
            background-color: @primary-color !important;
            color: #fff !important;
            font-weight: 500;
          }

          // 非当前月日期样式
          &.other-month {
            color: @text-placeholder !important;
            opacity: 0.6;
          }
        }
      }
    }
  }
}

// 学期颜色图例样式
.term-legend {
  padding: 8px 16px;
  background-color: @secondary-color;
  border-radius: @border-radius;
  margin-bottom: 8px;

  .legend-title {
    font-size: 0.85rem;
    color: @text-secondary;
    margin-bottom: 4px;
  }

  .legend-items {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
  }

  .legend-item {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 0.8rem;
    color: @text-primary;

    .color-dot {
      width: 12px;
      height: 12px;
      border-radius: 50%;
    }
  }
}

// 步骤指示器样式
.steps-indicator {
  display: flex;
  flex-direction: column;
  gap: @spacing-xs;
  margin: @spacing-md 0;
  padding: @spacing-md;
  background-color: #fff;
  border-radius: @border-radius;
  box-shadow: @shadow-sm;

  .step-progress-text {
    font-size: 0.9rem;
    color: @text-secondary;
    padding-left: @spacing-xs;
  }

  .step-container {
    display: flex;
    align-items: center;
    width: 100%;

    .step {
      display: flex;
      flex-direction: column;
      align-items: center;
      z-index: 2;

      .step-number {
        width: 28px;
        height: 28px;
        border-radius: 50%;
        background-color: #e5e6eb;
        color: @text-placeholder;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: @spacing-xs;
        font-size: 0.9rem;
        font-weight: 500;
        transition: all 0.3s;
      }

      .step-name {
        font-size: 0.85rem;
        color: @text-placeholder;
        transition: all 0.3s;
      }

      &.active {
        .step-number {
          background-color: @primary-color;
          color: #fff;
          transform: scale(1.1);
        }
        .step-name {
          color: @primary-color;
          font-weight: 500;
        }
      }

      &.completed {
        .step-number {
          background-color: #52c41a;
          color: #fff;
        }
        .step-name {
          color: #52c41a;
        }
      }
    }

    .step-line {
      flex: 1;
      height: 2px;
      background-color: #e5e6eb;
      margin: 0 @spacing-sm;
      transition: all 0.3s;

      &.completed {
        background-color: #52c41a;
      }
    }
  }
}

// 列表区域容器
.lists-container {
  display: flex;
  flex-direction: column;
  gap: @spacing-md;
}

// 列表卡片通用样式
.list-card {
  background-color: #fff;
  border-radius: @border-radius;
  box-shadow: @shadow-sm;
  overflow: hidden;
  transition: all 0.3s;

  &:hover {
    box-shadow: @shadow-md;
  }

  // 事件列表卡片特殊样式
  &.event-list-card {
    border-left: 4px solid @primary-color;
  }

  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: @spacing-sm @spacing-md;
    border-bottom: 1px solid @light-line;

    .list-title {
      margin: 0;
      font-size: 1rem;
      color: @text-primary;
      font-weight: 500;
    }

    :deep(.el-button) {
      transition: all 0.2s;
      &:hover {
        transform: translateY(-1px);
      }
    }
  }

  // 表格样式优化
  .content-table {
    :deep(.el-table) {
      width: 100% !important;
      border: none !important;
      --el-table-header-bg-color: @secondary-color;
      --el-table-header-text-color: @text-secondary;
      --el-table-row-hover-bg-color: rgba(64, 158, 255, 0.05);
    }

    :deep(.el-table__header-row) {
      height: 40px !important;
    }

    :deep(.el-table__body-row) {
      height: 38px !important;
      &:nth-child(even) {
        background-color: #fafbfc;
      }
    }

    :deep(.el-button) {
      margin-right: @spacing-xs;
      font-size: 0.8rem;
      padding: 0 8px;
      height: 24px;
      line-height: 24px;
    }
  }
}

// 空状态通用样式
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: @spacing-lg;
  gap: @spacing-sm;
  color: @text-placeholder;

  &.inside-card {
    padding: @spacing-lg 0;
    border-top: 1px dashed @light-line;
    margin-top: @spacing-sm;
  }

  &.inside-form {
    min-height: 200px;
  }

  &.inside-module {
    padding: @spacing-md 0;
    background-color: @secondary-color;
    border-radius: @border-radius;
  }

  .empty-icon {
    font-size: 2.5rem;
    line-height: 1;
  }

  .empty-text {
    font-size: 0.9rem;
    text-align: center;
  }

  .empty-action-btn {
    margin-top: @spacing-xs;
    transition: all 0.2s;
    &:hover {
      transform: translateY(-1px);
    }
  }
}

// 新增表单区域容器
.add-container {
  margin-top: @spacing-md;
}

// 表单卡片样式
.form-card {
  background-color: #fff;
  border-radius: @border-radius;
  box-shadow: @shadow-sm;
  overflow: hidden;

  .form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: @spacing-sm @spacing-md;
    border-bottom: 1px solid @light-line;

    h3 {
      margin: 0;
      font-size: 1rem;
      color: @text-primary;
      font-weight: 500;
    }

    .form-header-actions {
      display: flex;
      align-items: center;
      gap: @spacing-sm;

      .form-tip {
        font-size: 0.85rem;
        color: @text-secondary;
      }
    }

    :deep(.el-button) {
      transition: all 0.2s;
      &:hover {
        transform: translateY(-1px);
      }
    }
  }

  // 表单内容容器
  .form-content {
    padding: @spacing-md;

    &.term-form {
      background-color: @secondary-color;
      border-radius: @border-radius;
      margin-top: @spacing-sm;
    }

    &.event-form {
      background-color: #fafbfc;
      border-radius: @border-radius;
    }

    // 表单行样式
    .form-row {
      margin-bottom: @spacing-sm;
    }

    // 表单输入框统一样式
    .form-input {
      width: 100%;
      transition: all 0.2s;

      :deep(.el-input__inner),
      :deep(.el-select__inner),
      :deep(.el-input-number__input) {
        height: 36px;
        border-radius: 4px;
        border-color: @light-line;
        transition: all 0.2s;

        &:focus {
          border-color: @primary-color;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }
      }

      :deep(.el-date-editor) {
        width: 100% !important;
      }
    }

    // 表单按钮区域
    .form-buttons {
      display: flex;
      gap: @spacing-sm;
      justify-content: center;
      margin-top: @spacing-md;

      :deep(.el-button) {
        padding: 0 20px;
        height: 36px;
        transition: all 0.2s;

        &:hover {
          transform: translateY(-1px);
          box-shadow: @shadow-sm;
        }
      }
    }
  }

  // 学期列表样式
  .terms-list {
    padding: 0 @spacing-md;

    .terms-list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: @spacing-sm;

      h4 {
        margin: 0;
        font-size: 0.9rem;
        color: @text-primary;
      }
    }
  }

  // 步骤导航按钮区域
  .step-navigation {
    display: flex;
    justify-content: space-between;
    padding: @spacing-sm @spacing-md;
    border-top: 1px solid @light-line;

    :deep(.el-button) {
      padding: 0 16px;
      height: 36px;
      transition: all 0.2s;

      &:hover {
        transform: translateY(-1px);
        box-shadow: @shadow-sm;
      }

      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
        transform: none;
        box-shadow: none;
      }
    }
  }
}

// 事件模块容器
.term-event-modules {
  display: flex;
  flex-direction: column;
  gap: @spacing-md;
  padding: @spacing-md;
}

// 单个事件模块样式
.term-event-module {
  background-color: #fff;
  border: 1px solid @light-line;
  border-radius: @border-radius;
  overflow: hidden;
  transition: all 0.3s;

  &.active {
    border-color: @primary-color;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
  }

  // 模块头部
  .module-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: @spacing-sm @spacing-md;
    border-bottom: 1px solid @light-line;

    h4 {
      margin: 0;
      font-size: 0.95rem;
      color: @text-primary;

      .event-count {
        font-size: 0.8rem;
        color: @text-secondary;
        font-weight: normal;
        margin-left: @spacing-xs;
      }
    }

    :deep(.el-button) {
      transition: all 0.2s;
      &:hover {
        transform: translateY(-1px);
      }
    }
  }

  // 事件列表容器
  .event-list-container {
    padding: @spacing-md;
  }

  // 事件表单容器
  .event-form-container {
    padding: @spacing-md;
    border-top: 1px dashed @light-line;
  }
}

// 适配小屏幕响应式样式
@media (max-width: 1200px) {
  .multi-month-container {
    overflow-x: auto; // 小屏启用横向滚动
  }
}

@media (max-width: 768px) {
  .calendar-wrapper {
    padding: @spacing-sm;
  }

  .list-header,
  .form-header {
    flex-direction: column;
    align-items: flex-start;
    gap: @spacing-xs;

    .form-header-actions {
      width: 100%;
      justify-content: space-between;
    }
  }

  .step-container {
    flex-wrap: wrap;
    justify-content: center;
    gap: @spacing-md;

    .step-line {
      display: none;
    }
  }

  .term-event-module {
    padding: @spacing-xs;
  }
}
</style>
